package com.lgh.springframework.core.io;

import cn.hutool.core.lang.Assert;
import com.lgh.springframework.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname ClassPathResource
 * @description
 * @date 2023/02/24 23:51
 * <p>
 * ******************************************************
 */
public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.classLoader = null != classLoader ? classLoader : ClassUtils.getDefaultClassLoader();
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream inputStream = classLoader.getResourceAsStream(path);
        if (null == inputStream) {
            throw new FileNotFoundException(
                    this.path + " cannot be opened because it does not exist");
        }
        return inputStream;
    }

}
